package com.atguigu.ssyx.product.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.ssyx.product.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author ZhangYK
 * @version 8.0
 * @title FileUpdateServiceImpl
 * @description
 * @create 2024/7/7 14:41
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Value("${aliyun.endpoint}")
    private String endPoint;
    @Value("${aliyun.keyid}")
    private String accessKey;
    @Value("${aliyun.keysecret}")
    private String secreKey;
    @Value("${aliyun.bucketname}")
    private String bucketName;
    //上传文件
    @Override
    public String fileUpload(MultipartFile file) {


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint,accessKey,secreKey);

        try {
            InputStream inputStream = file.getInputStream();
            //1、bucket名字
            //2、上传文件路径+名称
            //例如 01.jpg
            // /aa/bb/01.jpg
            //3、获取文件输入流
            // 创建PutObjectRequest对象。

            //获取文件实际名称
            String objectName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            objectName=uuid+objectName;
            //对上传文件进行年月日分组
            //objectName：2024/07/07/01.jpg
            String currentDateTime = new DateTime().toString("yyyy/MM/dd");
            objectName = currentDateTime+"/"+objectName;

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //返回文件url
            //上传之后文件路径
            // https://ssyx-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endPoint+"/"+objectName;
            //返回
            return url;
        }catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
